package com.ucode.wap.cgms.controller;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ucode.cgms.service.CgmsCompanionUserService;
import com.ucode.cgms.service.CgmsSpecialZoneService;
import com.ucode.member.service.MemberService;
import com.ucode.model.cgms.CgmsCompanionUser;
import com.ucode.model.cgms.convert.CgmsCompanionUserConvert;
import com.ucode.model.cgms.enums.CgmsCompanionUserStatuzEnum;
import com.ucode.model.cgms.enums.CgmsCompanionUserWorkStateEnum;
import com.ucode.model.cgms.enums.CgmsSysResultCodeEnum;
import com.ucode.model.cgms.form.CgmsCompanionUserApplyForm;
import com.ucode.model.cgms.form.CgmsCompanionUserEditForm;
import com.ucode.model.cgms.vo.CgmsCompanionUserSimpleVO;
import com.ucode.model.member.Member;
import com.ucode.tool.annotation.NeedLogin;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.CommonAuditStatusEnum;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.base.enums.SexEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.wap.base.core.CurrentLoginUserHandler;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Tag(name = "移动端 - 陪玩社区系统 - 陪玩用户")
@RestController
@RequestMapping("/cgms/companion-user")
@Validated
public class ApiCgmsCompanionUserController {

    private static Log log = LogFactory.get();
    @Resource
    private CgmsCompanionUserService cgmsCompanionUserService;
    @Resource
    private MemberService memberService;
    @Resource
    private CgmsSpecialZoneService cgmsSpecialZoneService;
    @Resource
    private CurrentLoginUserHandler currentLoginUserHandler;

    @GetMapping(value = "/home/popularity-list")
    @Operation(summary = "首页人气陪玩列表")
    public ResponseResult<Paginator<CgmsCompanionUserSimpleVO>> popularityListByHome(@Schema(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                                     @Schema(description = "每页记录数", example = "5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Map<String,Object> condition = new HashMap<>();
        condition.put("statuzList", Arrays.asList(CgmsCompanionUserStatuzEnum.NORMAL.getCode(),CgmsCompanionUserStatuzEnum.FROZEN.getCode()));
        condition.put("deltag",false);
        condition.put("orderByStr", "order by orderCount desc");

        Paginator<CgmsCompanionUser> paginator = cgmsCompanionUserService.queryPageForList(condition,pageSize,pageNum);
        Paginator<CgmsCompanionUserSimpleVO> simpleVOPaginator = CgmsCompanionUserConvert.INSTANCE.convertSimplePage(paginator);
        return ResponseResult.success(simpleVOPaginator);
    }

    @GetMapping(value = "/home/benefit-list")
    @Operation(summary = "首页新人推荐列表")
    public ResponseResult<Paginator<CgmsCompanionUserSimpleVO>> newcomerListByHome(@Schema(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                              @Schema(description = "每页记录数", example = "5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Map<String,Object> condition = new HashMap<>();
        condition.put("statuzList", Arrays.asList(CgmsCompanionUserStatuzEnum.NORMAL.getCode(),CgmsCompanionUserStatuzEnum.FROZEN.getCode()));
        condition.put("deltag",false);
        condition.put("orderByStr", "order by processTime desc");

        Paginator<CgmsCompanionUser> paginator = cgmsCompanionUserService.queryPageForList(condition,pageSize,pageNum);
        Paginator<CgmsCompanionUserSimpleVO> simpleVOPaginator = CgmsCompanionUserConvert.INSTANCE.convertSimplePage(paginator);
        return ResponseResult.success(simpleVOPaginator);
    }

    @Operation(summary = "分页列表")
    @GetMapping(value = "/page-list")
    public ResponseResult<Paginator<CgmsCompanionUserSimpleVO>> pageList(
            @Schema(description = "昵称搜索") @RequestParam(value = "nickName", required = false) String nickName,
            @Schema(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数", example = "5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(nickName))
            condition.put("nickName", StrUtil.concat(true,"%", nickName,"%"));
        condition.put("statuzList", Arrays.asList(CgmsCompanionUserStatuzEnum.NORMAL.getCode(),CgmsCompanionUserStatuzEnum.FROZEN.getCode()));
        condition.put("deltag",false);

        Paginator<CgmsCompanionUser> paginator = cgmsCompanionUserService.queryPageForList(condition,pageSize,pageNum);
        Paginator<CgmsCompanionUserSimpleVO> simpleVOPaginator = CgmsCompanionUserConvert.INSTANCE.convertSimplePage(paginator);
        return ResponseResult.success(simpleVOPaginator);
    }


    @GetMapping(value = "/details/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "陪玩信息详情")
    public ResponseResult<CgmsCompanionUserSimpleVO> getDetails(@PathVariable(name="id",required=true) Long id) {
        CgmsCompanionUser companionUser = cgmsCompanionUserService.selectByPrimaryKey(id);
        CgmsCompanionUserSimpleVO simpleVO = CgmsCompanionUserConvert.INSTANCE.convertSimple(companionUser);
        return ResponseResult.success(simpleVO);
    }

    @NeedLogin(validate = true)
    @GetMapping(value = "/current-user/apply")
    @Operation(summary = "当前用户陪玩申请单")
    public ResponseResult<CgmsCompanionUser> getCurrentUserApply() {
        Long userId = currentLoginUserHandler.getCurrentUserId();
        return ResponseResult.success(cgmsCompanionUserService.selectByPrimaryKey(userId));
    }

    @NeedLogin(validate = true)
    @PostMapping("/current-user/submit-apply")
    @Operation(summary = "当前用户提交陪玩申请入驻")
    public ResponseResult<Object> submitApply(@Valid @RequestBody CgmsCompanionUserApplyForm form) {
        Long userId = currentLoginUserHandler.getCurrentUserId();
        CgmsCompanionUser companionUserDB = cgmsCompanionUserService.selectByPrimaryKey(userId);
        //验证用户是否已是陪玩用户
        if(ObjUtil.isNotNull(companionUserDB) && !companionUserDB.getDeltag()){

            //待审核
            if(ObjUtil.equals(companionUserDB.getAuditStatuz(), CommonAuditStatusEnum.SUBMIT_REVIEW.getCode())){
                throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_USER_UNDER_REVIEW);
            }

            //陪玩审核通过，且状态为正常或者冻结，则不能再次申请
            if(ObjUtil.equals(companionUserDB.getAuditStatuz(), CommonAuditStatusEnum.SUCCESS.getCode()) && (
                    ObjUtil.equals(companionUserDB.getStatuz(), CgmsCompanionUserStatuzEnum.NORMAL.getCode()) ||
                            ObjUtil.equals(companionUserDB.getStatuz(), CgmsCompanionUserStatuzEnum.FROZEN.getCode())
                    )){
                throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_USER_NOT_REAPPLY);
            }
        }

        CgmsCompanionUser companionUser = CgmsCompanionUserConvert.INSTANCE.convert(form);

        if(StrUtil.isNotBlank(companionUser.getIdCardNumber())){
            //从身份证中获取出生日期
            companionUser.setBirthday(IdcardUtil.getBirthDate(companionUser.getIdCardNumber()).toLocalDateTime().toLocalDate());
            //根据身份证号码获取性别
            companionUser.setGender(IdcardUtil.getGenderByIdCard(companionUser.getIdCardNumber()) == 1 ? SexEnum.MALE.getCode() : SexEnum.FEMALE.getCode());
        }

        companionUser.setId(userId);
        companionUser.setDeltag(false);
        companionUser.setType(2);
        companionUser.setAuditStatuz(CommonAuditStatusEnum.SUBMIT_REVIEW.getCode());
        companionUser.setStatuz(CgmsCompanionUserStatuzEnum.APPLY.getCode());
        companionUser.setWorkStatus(CgmsCompanionUserWorkStateEnum.REST.getCode());

        if(ObjUtil.isNotNull(companionUserDB)){
            cgmsCompanionUserService.update(companionUser);
        }else {
            cgmsCompanionUserService.insert(companionUser);
        }
        return ResponseResult.success();
    }


    @NeedLogin
    @GetMapping(value = "/current-companion-user/info")
    @Operation(summary = "当前陪玩用户信息详情")
    public ResponseResult<CgmsCompanionUserSimpleVO> getCurrentCompanionUserInfo() {
        Long userId = currentLoginUserHandler.getCurrentUserId();
        CgmsCompanionUser companionUser = cgmsCompanionUserService.selectByPrimaryKey(userId);
        CgmsCompanionUserSimpleVO simpleVO = CgmsCompanionUserConvert.INSTANCE.convertSimple(companionUser);

        return ResponseResult.success(simpleVO);
    }

    @NeedLogin(validate = true)
    @PostMapping("/edit")
    @Operation(summary = "陪玩信息编辑")
    public ResponseResult<Object> edit(@Valid @RequestBody CgmsCompanionUserEditForm form) {
        Long userId = currentLoginUserHandler.getCurrentUserId();
        cgmsCompanionUserService.validateCompanionUser(userId);
        CgmsCompanionUser companionUser = CgmsCompanionUserConvert.INSTANCE.convert(form);
        companionUser.setId(userId);
        cgmsCompanionUserService.update(companionUser);

        //同步修改用户昵称、头像
        Member member = new Member();
        member.setId(userId);
        member.setNickname(companionUser.getNickName());
        member.setAvatar(companionUser.getAvatar());
        member.setGender(companionUser.getGender());
        member.setWechatId(companionUser.getWechatId());
        member.setBirthday(companionUser.getBirthday());
        memberService.update(member);

        return ResponseResult.success();
    }

    @NeedLogin(validate = true)
    @PostMapping("/switch-work-state")
    @Operation(summary = "陪玩切换工作状态")
    public ResponseResult<Object> SwitchWorkState(@Schema(description = "工作状态:1工作中 2 休息中",requiredMode = Schema.RequiredMode.REQUIRED)
                                                      @RequestParam(value = "workState",required=true) Integer workState) {

        if(ObjUtil.isNull(CgmsCompanionUserWorkStateEnum.getByCode(workState)))
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);

        Long userId = currentLoginUserHandler.getCurrentUserId();
        cgmsCompanionUserService.validateCompanionUser(userId);
        CgmsCompanionUser companionUser = new CgmsCompanionUser();
        companionUser.setId(userId);
        companionUser.setWorkStatus(workState);
        cgmsCompanionUserService.update(companionUser);

        return ResponseResult.success();
    }


}
